package com.huatai.exchange.receive;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.mail.utils.MailClientUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import java.util.List;
import java.util.Map;

@Service("fileDataMailReceiveService")
public class FileDataMailReceiveServiceImpl extends AbstractFileDataReceiveService {


    @Value("${tmp_file_path}")
    private String tmpFilePath;


    /**
     * @param srcPath    获取地址，邮箱， smb地址， http URL ftp 地址
     * @param srcName    获取文件匹配名称
     * @param markName   邮件标题匹配
     * @param fileSuffix
     * @param tmpDirPath
     * @param resvMap    其他参数
     * @return
     * @throws BusinessException
     */
    @Override
    List<String> findAndDownloadFileList(String srcPath, String srcName, String markName, String fileSuffix, String tmpDirPath, Map<String, Object> resvMap) throws BusinessException {
        List<String> strs = Lists.newArrayList();
        Store store = null;
        Folder folder = null;
        try {
            logger.info("开始连通邮箱");
            if (srcName.contains("@")) {
                throw new BusinessException("未开发");
            }
            store = MailClientUtils.constructorDefaultStore();
            folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] messages = folder.getMessages();
            // 从最后一个 邮件开始扫描
            logger.info("读取邮件数量[" + messages.length + "]");
            List<String> fromMails = Lists.newArrayList(srcPath.split("\\|"));
            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];

                String subject = message.getSubject();
//                logger.info("邮件标题：[" + subject + "]");
                if (StringUtils.isBlank(subject) || !subject.contains(markName)) {
                    continue;
                }
                // 判断是否是邮箱白名单
                logger.info("判断是否是邮箱白名单[" + srcPath + "]");
                String fromMail = ((InternetAddress) (message.getFrom()[0])).getAddress();
                logger.info("发件人[" + fromMail + "]");
                if (!fromMails.contains(fromMail)) {
                    continue;
                }
                if (!MailClientUtils.isContainAttachment(message)) {
                    // 无文件 跳过
                    continue;
                }
                strs.addAll(MailClientUtils.saveAttachment(message, tmpDirPath,srcName));
                logger.info("文件地址：" + JSON.toJSONString(strs));
                break;
            }
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            MailClientUtils.close(folder, store);
        }
        return strs;
    }
}
